<template>
  <a-form
    ref="stepForm2Ref"
    :model="formData"
    layout="vertical"
    :wrapperCol="{ span: 24 }"
    labelAlign="left"
    :hideRequiredMark="false"
    :rules="rules"
    :scrollToFirstError="true"
    style="margin-top: 20px"
  >
    <a-col :span="24">
      <a-form-item label="渠道码是否可见" name="isChannelDisplay">
        <a-radio-group
          v-model:value="formData['isChannelDisplay']"
          :disabled="props.isDisabled"
        >
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-col>
    <a-tabs v-model:activeKey="activeKey" style="margin-top: 20px;">
      <a-tab-pane key="1" :disabled="props.isDetail">
        <template #tab>
          <span>单个商户上传</span>
        </template>
      </a-tab-pane>
      <a-tab-pane key="2" :disabled="props.isDetail">
        <template #tab>
          <span>多个商户上传</span>
        </template>
      </a-tab-pane>
    </a-tabs>

    <a-row type="flex" justify="space-between" wrap="true">
      <a-row v-if="activeKey === '1'" style="margin:20px 0 30px;">
        <a-col :span="18">
          <a-input
            v-model:value="formData['singleMchNo']"
            placeholder="请输入商户号"
            allowClear
          />
        </a-col>
        <a-col :span="4" style="padding: 0 20px">
          <a-button
            type="primary"
            style="padding: 0 20px"
            :disabled="props.isDetail"
            @click="handleAddMch"
          >
            新增
          </a-button>
        </a-col>
      </a-row>

      <a-col v-if="activeKey === '2'" :span="24">
        <a-form-item name="fileList">
          <template #label>
            <span style="margin-right: 20px">文件上传</span>
            <a-button
              class="item"
              type="link"
              style="padding: 4px 0"
              href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/template/writable_merchants.xlsx"
            >
              下载可核销商户模板
            </a-button>
          </template>
          <a-upload-dragger
            v-model:fileList="formData['fileList']"
            :action="uploadAction"
            :data="uploadParams"
            :maxCount="1"
            accept=".xlsx, .xls"
            name="file"
            :beforeUpload="beforeUpload"
            @change="uploadChange"
          >
            <p class="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
            <p class="ant-upload-hint">
              <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
            </p>
          </a-upload-dragger>
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item name="mchList" label="可核销商户清单">
          <page-header-wrapper>
            <a-card class="table-card">
              <GzSearchForm 
                :searchFunc="handleSearch" 
                :resetFunc="handleReset" 
                searchConditionNum="6"
              >
                <gz-text-up
                  v-model:value="searchParams.mchNo"
                  placeholder="商户号"
                  style="width: 200px"
                />
              </GzSearchForm>
              <GzTable
                ref="tableRef"
                :table-columns="tableColumns"
                :init-data="true"
                :req-table-data-func="fetchTableData"
                :search-data="searchParams"
                :scrollX="600"
                rowKey="mchNo"
                size="small"
              >
                <template #topBtnSlot>
                  <a-button type="primary" :disabled="props.isDetail" @click="handleDeleteAll">删除所有可核销商户</a-button>
                </template>
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key == 'belongToHkMch'">
                    <span v-if="record.belongToHkMch==''">--</span>
                    <span v-if="record.belongToHkMch==1">是</span>
                    <span v-if="record.belongToHkMch==0">否</span>
                  </template>
                  <template v-if="column.key == 'isChannelDisplay'">
                    <GzTableColState :state="record.isChannelDisplay" :disabled="props.isDetail" :show-switch-type="$access('ENT_SCORE_RULE_INFO_EDIT')" :on-change="(isChannelDisplay) => { return stateChangeFunc(record.awardMchId, isChannelDisplay)}" />
                  </template>

                  <template v-if="column.key === 'operation'">
                    <a-button
                      type="link"
                      danger
                      :disabled="props.isDetail"
                      @click="handleDelete(record)"
                    >
                      删除
                    </a-button>
                  </template>
                </template>
              </GzTable>
            </a-card>
          </page-header-wrapper>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, reactive, computed,getCurrentInstance,nextTick} from 'vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import{$couponAddAwardMch,$getMchList,$couponDeleteAllMch,$couponDeleteMch,$couponImportMch,$updateMchDestroyState }from '@/api/awardMange/coupon/index'
import {$getUploadFormParams} from '@/api/components/GzUpload/index'
const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

// 定义props
const props = defineProps({
  // 奖品id
    awardId: {
    type: String,
    default:'',
    
  },
  // 奖品类型
  awardType: {
    awardType: Number,
    default:0,
  },
  isDisabled:{
    type:Boolean
  },
  isDetail:{
    type:Boolean,
    default:false
  }

})

console.log(props.awardId,'props.awardId')

// const emit = defineEmits(['update:modelValue', 'add-merchant', 'delete-merchant', 'delete-all', 'upload-success', 'upload-error','before-upload'])
  
const formData = ref({
  ossFileUrl:'',
  isChannelDisplay:1,
}) 
// 表单引用
const stepForm2Ref = ref()
// 表格引用
const tableRef = ref()

// 当前激活的tab
const activeKey = ref('1')

// 搜索参数
const searchParams = reactive({
  mchNo: '',

})
const uploadAction = ref()
const uploadParams = ref()

// 可核销商户表格
const tableColumns = [
  { title: '商户号', dataIndex: 'mchNo', key: 'mchNo' },
  { title: '渠道码可见是否开启', dataIndex: 'isChannelDisplay', key: 'isChannelDisplay', align: 'center' },
  { title: '操作', dataIndex: 'operation', key: 'operation', align: 'center' },
]

// 只有awardType为0，则显示“是否关联海科通道”列
const isHkMchColumnVisible = computed(() => props.awardType === 0)
if (isHkMchColumnVisible.value) {
  tableColumns.splice(1, 0, { title: '是否关联海科通道', dataIndex: 'belongToHkMch', key: 'belongToHkMch', align: 'center' })
} 


const rules = ref(
  {
      // mchList: [{ required: true, trigger: 'blur', validator: mchListValidator }],
      isChannelDisplay:[{ required: true, message: '', trigger: 'change' }]
  }
)

// 是否存在可核销商户
const hasMch = ref(false)
/** 可核销商户上传校验 */
// function mchListValidator() {
//   if (hasMch.value) {
//     // 存在可核销商户
//     return Promise.resolve()
//   } else {
//     return Promise.reject('请上传可核销商户清单')
//   }
// }
  
// 请求table接口数据
function fetchTableData(params) {
  return new Promise((resolve) => {
    $getMchList({
        ...params,
        awardId: props.awardId,
        awardType:props.awardType,
      })
      .then((res) => {
        hasMch.value = res.records.length
        resolve(res)
      })
  })
}

function stateChangeFunc(awardMchId,isChannelDisplay){

  $updateMchDestroyState({awardMchId,isChannelDisplay}).then(res => { 
       $infoBox.message.success('修改成功')
       tableRef.value.refTable(false)
 })
}
// 添加商户
const handleAddMch = () => {
  if (!formData.value.singleMchNo) {
    message.warning('请输入商户号')
    return
  }
  
 $couponAddAwardMch( {
      awardId: props.awardId,
      mchNo: formData.value.singleMchNo,
      awardType:props.awardType,
      isChannelDisplay:formData.value.isChannelDisplay
    })
    .then((res) => {
      formData.value.singleMchNo = ''
        formData.value.isChannelDisplay=1
      nextTick(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('新增成功')
      })
    })
}

// 删除商户
const handleDelete = (record) => {
    $infoBox.confirmDanger('确认删除？', '请确认是否删除当前可核销商户？', () => {
    $couponDeleteMch({ awardMchId: record.awardMchId })
      .then(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
  })
}

// 删除所有商户
const handleDeleteAll = () => {
 
  $infoBox.confirmDanger('确认删除？', '请确认是否删除所有可核销商户？', () => {
    $couponDeleteAllMch( { awardId:props.awardId,awardType:props.awardType})
      .then(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
  })
}

console.log(props.isDisabled1,'props.isDisabled')

// 搜索
const handleSearch = () => {
  tableRef.value.refTable(true)

}

// 重置搜索
const handleReset = () => {
  searchParams.mchNo = ''
}

/**
 * 文件上传
 */
 function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'activity').then((res) => {
    uploadAction.value = res.formActionUrl // action
    uploadParams.value= res.formParams //表单组件
    formData.value.ossFileUrl = res.ossFileUrl
  })
}

// 上传状态改变
const uploadChange = (info) => {  
 if (info.file.status === 'error') {
    // 上传异常
   formData.value.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }
  if (info.file.status === 'done') {
    
   // 请求可核销商户接口
   $couponImportMch( {
      awardId: props.awardId,
      url: formData.value.ossFileUrl,
      awardType:props.awardType,
    })
    .then((res) => {
      if (res.okList?.length) {
        tableRef.value.refTable(true)
      }
      if (res.errList?.length) {
        nextTick(() => {  // 部分失败时也需要刷新列表
          tableRef.value.refTable(true)
        })
        return $infoBox.message.error('导入失败：' + res.errList.join('、'))
      }
      // 刷新可核销商户列表
      nextTick(() => {
        tableRef.value.refTable(true)
        $infoBox.message.success('导入成功')
      })
    })
  }
}

function validate (){
  return stepForm2Ref.value.validate()
}
defineExpose({
 validate,
})


</script>

<style lang="less" scoped>
.table-card {
  margin-top: 20px;
}
:deep(.table-layer .table-search-item) {
  width: calc(100% / 3);
}
</style>